package com.xiaouyudeguang.common.manager;

import com.xiaouyudeguang.common.exception.BusinessException;
import com.xiaouyudeguang.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class WebSocketSessionManager {
    /**
     * 保存连接 session 的地方
     */
    public  static ConcurrentHashMap<String, WebSocketSession> SESSION_POOL = new ConcurrentHashMap<>();

    /**
     * 添加 session
     *
     * @param key
     */
    public static void add(String key, WebSocketSession session) throws BusinessException {
        Map<String, String> pathVars = parsePathVars(session.getUri());
        String userId = pathVars.get("userId");
        if (StringUtils.isBlank(userId)) {
            throw new BusinessException("参数错误");
        }
        SESSION_POOL.put(userId, session);
        SESSION_POOL.put(key, session);
    }

    /**
     * 删除 session,会返回删除的 session
     *
     * @param key
     * @return
     */
    public static WebSocketSession remove(String key) throws BusinessException {
        WebSocketSession session = SESSION_POOL.get(key);
        Map<String, String> pathVars = parsePathVars(session.getUri());
        String userId = pathVars.get("userId");
        if (StringUtils.isBlank(userId)) {
            throw new BusinessException("参数错误");
        }
        SESSION_POOL.remove(userId);
        SESSION_POOL.remove(key);
        return session;
    }

    /**
     * 删除并同步关闭连接
     *
     * @param key
     */
    public static void removeAndClose(String key) throws BusinessException {
        WebSocketSession session = remove(key);
        try {
            // 关闭连接
            session.close();
        } catch (IOException e) {
            // todo: 关闭出现异常处理
            e.printStackTrace();
        }
    }

    /**
     * 获得 session
     *
     * @param key
     * @return
     */
    public static WebSocketSession get(String key) {
        return SESSION_POOL.get(key);
    }

    public static Map<String, String> parsePathVars(URI uri) {
        Map<String, String> pathVars = new HashMap<>();
        if (uri == null){
            return pathVars;
        }
        String[] arr = uri.getQuery().substring(uri.getQuery().indexOf("?") + 1).split("&");
        for (String str : arr) {
            pathVars.put(str.split("=")[0], str.split("=")[1]);
        }
        return pathVars;
    }
}
